import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { defineComponent, ref } from 'vue'
import { isNumber } from 'lodash'
// import { useStore } from 'vuex'
import { ElUpload, ElImageViewer, genFileId, ElMessage } from 'element-plus'
import { getToken } from '~/utils/auth'
import styles from './index.module.scss'

export default defineComponent({
  name: 'BaseUpload',
  props: [
    'action',
    'headers',
    'method',
    'multiple',
    'data',
    'name',
    'withCredentials',
    'showFileList',
    'drag',
    'accept', // 上传文件类型 参数类型 '.xlsx' | '.xls' | 'image/*' | '.doc' | 'docx' | '.pdf'
    'maxSize', // 最大文件大小 单位byte
    'onPreview',
    'onRemove',
    'onSuccess',
    'onError',
    'onProgress',
    'onChange',
    'onExceed',
    'beforeUpload',
    'beforeRemove',
    'fileList',
    'listType',
    'autoUpload',
    'httpRequest',
    'disabled',
    'limit'
  ],
  setup(props, { slots }) {
    const uploadRef = ref<UploadInstance>()
    const previewFileUrl = ref<string>()

    const handleExceed: UploadProps['onExceed'] = async (files, uploadFiles) => {
      if (uploadFiles?.length === props?.limit) {
        await uploadRef.value?.handleRemove(uploadFiles[0] as UploadRawFile)
      }
      const file = files[0] as UploadRawFile
      file.uid = genFileId()
      uploadRef.value!.handleStart(file)
      uploadRef.value!.submit()
    }

    // 上传前文件处理函数
    const handleBeforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
      // 默认最大文件大小为 16mb
      const { accept, maxSize = 16 * 1024 * 1024 } = props

      if (isNumber(maxSize) && rawFile.size > maxSize) {
        ElMessage.error('文件超出大小范围！')
        return false
      }

      if (!accept) return true

      let flag = false
      // 判断是否为excel
      if (
        (accept!.includes('.xlsx') || accept!.includes('.xls')) &&
        (rawFile.type === 'application/vnd.ms-excel' ||
          rawFile.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
      ) {
        flag = true
      } else if (accept!.includes('image/*') && rawFile.type!.includes('image')) {
        // 判断是否为图片
        flag = true
      } else if (
        (accept!.includes('.jpg') && rawFile.type!.includes('jpeg')) ||
        (accept!.includes('.png') && rawFile.type!.includes('png'))
      ) {
        // 判断是否为jpg,png图片
        flag = true
      } else if (
        (accept!.includes('.doc') || accept!.includes('.docx')) &&
        (rawFile.type ===
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
          rawFile.type === 'application/msword')
      ) {
        // 判断是否为word
        flag = true
      } else if (accept!.includes('.pdf') && rawFile.type!.includes('application/pdf')) {
        // 判断是否为pdf
        flag = true
      }

      if (!flag) {
        ElMessage.error('文件类型不匹配!')
      }
      return flag
    }

    // 删除前文件处理函数
    // const handleBeforeRemove = async (file: Record<string, any>) => {
    //   if (props.beforeRemove) {
    //     return props.beforeRemove() as any
    //   }

    //   if (file?.response?.data?.id) {
    //     const result = await store.dispatch('global/RemoveFiles', { ids: file?.response?.data?.id })
    //     if (result?.code === 200) return true
    //     return false
    //   }
    // }

    // 查看文件处理函数
    const handlePreviewFile: UploadProps['onPreview'] = (file) => {
      previewFileUrl.value = (file?.response as any)?.data?.link || file?.url
    }

    return () => (
      <>
        <ElUpload
          {...props}
          ref={uploadRef}
          class={{
            'base-upload-template': true,
            [styles['base-upload']]: true,
            [styles['limit-max-upload']]: props.fileList?.length === props.limit
          }}
          action={props?.action || '/api/gxsaas-system/oss/endpoint/put-file'}
          headers={props?.headers || { 'gxsaas-Auth': `bearer ${getToken()}` }}
          onExceed={props?.limit && handleExceed}
          beforeUpload={props.beforeUpload || handleBeforeFileUpload}
          // beforeRemove={handleBeforeRemove as any}
          onPreview={handlePreviewFile}
        >
          {slots}
        </ElUpload>
        {!!previewFileUrl.value && (
          <ElImageViewer
            teleported
            urlList={[previewFileUrl.value]}
            onClose={() => {
              previewFileUrl.value = undefined
            }}
          />
        )}
      </>
    )
  }
})
